package com.ftx.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Created by fengtingxin on 2020/7/21.
 */
@Component
public class SpringUtils implements ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(SpringUtils.class);

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext = applicationContext;
    }

    public static Object getBean(String beanName) {
        if (applicationContext == null) {
            logger.error("未初始化Spring上下文");
            return null;
        } else if (!applicationContext.containsBean(beanName)) {
            logger.warn("Spring上下文中不存在要查找的对象[{}]", beanName);
            return null;
        } else {
            return applicationContext.getBean(beanName);
        }
    }
}
